<?php

namespace ZfcUser\Controller;

use Zend\Form\Form;
use Zend\Mvc\Controller\AbstractActionController;
use Zend\Stdlib\ResponseInterface as Response;
use Zend\Stdlib\Parameters;
use Zend\View\Model\ViewModel;
use ZfcUser\Service\User as UserService;
use ZfcUser\Model\TforgotpasswordtokensTable;
use ZfcUser\Model\Tforgotpasswordtokens;
use ZfcUser\Model\TuserTable;
use ZfcUser\Model\Tuser;
use ZfcUser\Model\TusertypeTable;
use ZfcUser\Model\Tusertype;
use ZfcUser\Model\TcountryTable;
use ZfcUser\Model\Tcountry;
use ZfcUser\Model\TstateTable;
use ZfcUser\Model\Tstate;
use Zend\Authentication\AuthenticationService;
use SanAuthWithDbSaveHandler\Storage\IdentityManagerInterface;
use ZfcUser\Options\UserControllerOptionsInterface;
use Zend\View\Model\JsonModel;
use Zend\Cache\StorageFactory;
class UserController extends AbstractActionController
{
    const ROUTE_CHANGEPASSWD = 'zfcuser/changepassword';
    const ROUTE_LOGIN        = 'auth';
    const ROUTE_REGISTER     = 'zfcuser/register';
    const ROUTE_CHANGEEMAIL  = 'zfcuser/changeemail';
    const CONTROLLER_NAME    = 'zfcuser';
    protected $failedLoginMessage = 'Authentication failed. Please try again.';
    protected $options;
	protected $authService;
    protected $identityManager;
    public function indexAction()
    {
		//$this->getServiceLocator()->get('memcached')->setItem('foo', 'bar');
		//echo $this->getServiceLocator()->get('memcached')->getItem('bar');exit;
		//$manager = $this->getServiceLocator()->get('MemorySharedManager');
		//$manager->setStorage('memcached', array('host' => '127.0.0.1', 'port' => 11211));
		//$manager->write('my-identifier', "fddfdfdf");
		//$object = $manager->read('my-identifier');
		//echo "<pre>";print_r($object);exit;
        if (!$this->zfcUserAuthentication()->hasIdentity()) {
            return $this->redirect()->toRoute(static::ROUTE_LOGIN);
        }
        return new ViewModel();
    }
	public function forgotPasswordAction()
    {				
			$result = new ViewModel();
			$result->setTerminal(true);
			return $result;		
    }
	public function sentforgotRequestAction(){
		global $forgotPasswordSubject;
		global $frogotPasswordMessage;
		if(isset($_POST['email']) && $_POST['email']!="")
		{
			$table = $this->getServiceLocator()->get('ZfcUser\Model\TuserTable');
			$getUserdetais = $table->getuserid($_POST['email']);
			$username=ucfirst($getUserdetais->first_name);			
			$to=$_POST['email'];			
			$token='';
			$token = $this->getUniqueCode('10');
			$frogotPasswordMessage = str_replace("<FULLNAME>","$username", $frogotPasswordMessage);
			$frogotPasswordMessage = str_replace("<PASSWORDLINK>","http://" . $_SERVER['HTTP_HOST']."/user/reset-password?token=".$token, $frogotPasswordMessage);
			$frogotPasswordMessage = str_replace("<EMILADDRESS>","$to", $frogotPasswordMessage);			
			if(sendMail($to,$forgotPasswordSubject,$frogotPasswordMessage)){
				$tokentable=$this->getServiceLocator()->get('ZfcUser\Model\TforgotpasswordtokensTable');
				$addToken=$tokentable->addToken($id='',$getUserdetais->user_id,$getUserdetais->email_id,$token);
				if($addToken>0){
					$result = new JsonModel(array(					
							'output' => 'success',
					));	
				}else{
					$result = new JsonModel(array(					
							'output' => 'notsuccess',
					));	
				}				
			}
			return 	$result;		
		}
	}
	public function resetPasswordAction()
    {		
		if(isset($_GET['token'])&& $_GET['token']!=''){
			$tokentable=$this->getServiceLocator()->get('ZfcUser\Model\TforgotpasswordtokensTable');
            $tokendetails=$tokentable->getTokenDetails($_GET['token']);
			$tokendetail=array();
			if(count($tokendetails)){
				foreach($tokendetails as $details){
					$tokendetail=$details;
				}
				return new ViewModel(array(
					'tokendetail'=>$tokendetail,
					'error'=>0,
					)
				);
			}else{
				return new ViewModel(array(
					'tokendetail'=>$tokendetail,
					'error'=>1,
					)
				);
			}
		}else{
			return $this->redirect()->toUrl('/');
		}	
    }
	public function getUniqueCode($length = "")
	{
		$code = md5(uniqid(rand(), true));
		if ($length != "")
		return substr($code, 0, $length);
		else
		return $code;
	}
	public function homeAction(){
		return new ViewModel();
	}	
    public function loginAction()
    {		
		$checkLogin=Array();
		if (isset($_POST['userEmail'])){	
			$user=array();
			$table = $this->getServiceLocator()->get('ZfcUser\Model\TuserTable');
			$sessiontable = $this->getServiceLocator()->get('ZfcUser\Model\TsessionTable');
			$checkLogin = $table->checkLogin($_POST);
			if($checkLogin!=""){
			if(isset($_POST['session_id']) && $_POST['session_id']!='')
			{
				$sessiontable->deleteExistsSession($_POST['session_id']);
			}
			$isexists = $sessiontable->checkSessionExists($checkLogin->user_id);
				$redirect_url='';
				if(isset($_SESSION['redirecturl']) && $_SESSION['redirecturl']!='')
				{
				$redirect_url=$_SESSION['redirecturl'];
				}
				if(!$isexists->count())
				{
				$table = $this->getServiceLocator()->get('ZfcUser\Model\TusertypeTable');
				$getuser_type_name = $table->getusertypename($checkLogin->user_type_id);
				$getuser_type_name->name;		
				$_SESSION['user']['email']=$checkLogin->email_id;
				$_SESSION['user']['userId']=$checkLogin->user_id;
				$_SESSION['user']['name']=$checkLogin->first_name;
				$_SESSION['user']['user_photo']=$checkLogin->user_photo;
				$_SESSION['user']['user_type_id']=$checkLogin->user_type_id;
				$_SESSION['user']['user_type_name']=$getuser_type_name->name;
				$sessiontable->updateUserID(session_id(),$checkLogin->user_id);
				
				//echo $redirect_url;exit;				
				$result = new JsonModel(array(					
					'output' 		=> 'success',
					'userTypeId'	=>	$_SESSION['user']['user_type_id'],
					'redirect_url'  => $redirect_url,
					'loginuserexists'=>'0',
				));
			  }
			else
			{
				$current_session=$isexists->current();
				$result = new JsonModel(array(					
					'loginuserexists' 		=> '1',
					'redirect_url'  => $redirect_url,
					'session_id'=>$current_session->id,
					
				));
			}			
			}else{				
				$result = new JsonModel(array(					
					'output' => 'notsuccess',
				));
			}
			return $result;
		}else{
			$_SESSION['redirecturl']=$_SERVER['HTTP_REFERER'];
			$result = new ViewModel(array(					
				'output' => 'succusses',			
			));
			$result->setTerminal(true);
			return $result;
		}
	}
    public function authenticateAction()
    {
        if ($this->zfcUserAuthentication()->getAuthService()->hasIdentity()) {
            return $this->redirect()->toRoute($this->getOptions()->getLoginRedirectRoute());
        }

        $adapter = $this->zfcUserAuthentication()->getAuthAdapter();
        $redirect = $this->params()->fromPost('redirect', $this->params()->fromQuery('redirect', false));

        $result = $adapter->prepareForAuthentication($this->getRequest());

        // Return early if an adapter returned a response
        if ($result instanceof Response) {
            return $result;
        }

        $auth = $this->zfcUserAuthentication()->getAuthService()->authenticate($adapter);

        if (!$auth->isValid()) {
            $this->flashMessenger()->setNamespace('zfcuser-login-form')->addMessage($this->failedLoginMessage);
            $adapter->resetAdapters();
            return $this->redirect()->toUrl($this->url()->fromRoute(static::ROUTE_LOGIN)
                . ($redirect ? '?redirect='. rawurlencode($redirect) : ''));
        }

        if ($this->getOptions()->getUseRedirectParameterIfPresent() && $redirect) {
            return $this->redirect()->toUrl($redirect);
        }

        return $this->redirect()->toRoute($this->getOptions()->getLoginRedirectRoute());
    }
	public function checkEmailAction()
	{	
		if(isset($_POST['email']) && $_POST['email']!=""){
			$table = $this->getServiceLocator()->get('ZfcUser\Model\TuserTable');
			$countemail = $table->checkEmail($_POST['email'],'user');			
			if($countemail != 0){
				$result = new JsonModel(array(					
					'output' => 'success',
				));	
			}else{
				$result = new JsonModel(array(					
					'output' => 'notsuccess',
				));	
			}
			return $result;
		}
	}
	public function updateBoardClassAction(){
		global $regSubject;
		global $regMessage;
		$userEmail=array();	
		if(isset($_POST['classId']) && $_POST['classId']!=''){
			$table = $this->getServiceLocator()->get('ZfcUser\Model\TuserTable');			
			$user = $table->updateBoardClassUser($_POST);
			$user_details=$table->getuserdetails($_SESSION['user']['userId']);
			$user_info=$user_details->current();			
			$username=ucfirst($user_info->first_name);					
			$to=$user_info->email_id;
			$userEmail=explode("@",$user_info->email_id);
			$password=$userEmail[0];
			$boardname=$user_info->board_name;
			$classname=$user_info->class_name;			
			$regMessage = str_replace("<FULLNAME>","$username", $regMessage);
			$regMessage = str_replace("<ACTIVATIONLINK>","http://" . $_SERVER['HTTP_HOST']."/user/change-password?id=".$user_info->user_id."&token=".$password, $regMessage);		
			$regMessage = str_replace("<EMILADDRESS>","$to", $regMessage);
			$regMessage = str_replace("<PASSWORD>","$password", $regMessage);
			$regMessage = str_replace("<BOARDNAME>","$boardname", $regMessage);
			$regMessage = str_replace("<CLASSNAME>","$classname", $regMessage);			
			$redirect_url='';						
			if(sendMail($to,$regSubject,$regMessage)){
				if(isset($_SESSION['redirecturl']) && $_SESSION['redirecturl']!=''){
				$redirect_url=$_SESSION['redirecturl'];
				}
				$result = new JsonModel(array(					
				'output' 		=> 'success',
				'redirect_url'	=>	$redirect_url,
				));					
			}else{
				$result = new JsonModel(array(					
					'output' => 'notsuccess',
					
				));	
			}			
			return $result;
		}
	}
    public function registerAction()
    {
		$userEmail=array();		
		if(isset($_POST['name']) && $_POST['name']!=''){			
			$userEmail=explode("@",$_POST['emailId']);					
			$table = $this->getServiceLocator()->get('ZfcUser\Model\TuserTable');
			$countemail = $table->checkEmail($_POST['emailId'],'user');
			if($countemail == 0){
				$user = $table->addUser($_POST,$userEmail[0],'user');			
				$tokentable=$this->getServiceLocator()->get('ZfcUser\Model\TforgotpasswordtokensTable');
				$tokenId=$tokentable->addToken($id='',$user->user_id,$user->email_id,$userEmail[0]);							
				if(count($user)!=0){
					$table = $this->getServiceLocator()->get('ZfcUser\Model\TuserTable');
					$checkreg = $table->checkregLogin($_POST['emailId'],$userEmail[0]);
					if($checkreg!=""){
						$table = $this->getServiceLocator()->get('ZfcUser\Model\TusertypeTable');
						$getuser_type_name = $table->getusertypename($checkreg->user_type_id);
						$getuser_type_name->name;		
						$_SESSION['user']['email']=$checkreg->email_id;
						$_SESSION['user']['userId']=$checkreg->user_id;
						$_SESSION['user']['name']=$checkreg->first_name;
						$_SESSION['user']['user_photo']=$checkreg->user_photo;
						$_SESSION['user']['user_type_id']=$checkreg->user_type_id;
						$_SESSION['user']['user_type_name']=$getuser_type_name->name;	
						$redirect_url='';
						if(isset($_SESSION['redirecturl']) && $_SESSION['redirecturl']!='')
						{
							$redirect_url=$_SESSION['redirecturl'];
						}
						$result = new JsonModel(array(					
							'output' => 'success',
							'redirect_url'=>$redirect_url,
							'email'=>$_SESSION['user']['email'],
						));
					}else{
						$result = new JsonModel(array(					
							'output' => 'notsuccess',								
						));
					}
				}
			}else{
					$result = new JsonModel(array(					
						'output' => 'mailExists',
					));	
				}				
			return $result;
		}else{
			$table = $this->getServiceLocator()->get('ZfcUser\Model\TcountryTable');
			$countries=$table->getallcountries();
			$table = $this->getServiceLocator()->get('ZfcUser\Model\TusertypeTable');
			$getuser_type=$table->getuserTypes();
			$_SESSION['redirecturl']=$_SERVER['HTTP_REFERER'];			
			$result = new ViewModel(array(					
				'usertypes' => $getuser_type,
				'countries' => $countries,				
			));
			$result->setTerminal(true);
			return $result;
		}
    }
	
    public function changePasswordAction()
    {
        if(isset($_GET['id']) && $_GET['id']!=""){
			$token='';
			$status=array();
			$table = $this->getServiceLocator()->get('ZfcUser\Model\TuserTable');
			$user = $table->activeUser($_GET['id']);
			$tokentable=$this->getServiceLocator()->get('ZfcUser\Model\TforgotpasswordtokensTable');
			$statuss = $tokentable->getTokenDetails($_GET['token']);						
			foreach($statuss as $status){}			
			if($status->status == 0){
				return $this->redirect()->toUrl('/user/error-already-active');
			}else{
				$tokentable->addToken($status->id,$status->user_id,$status->email_id,$token,'update');
			}
		}else if(isset($_POST['userId'])|| isset($_GET['userId'])){
			if(isset($_POST['userId'])){
				$userid=$_POST['userId'];
			}else{
				$userid=$_GET['userId'];
			}
			if(isset($_POST['cnfpwrd'])){			
				$table = $this->getServiceLocator()->get('ZfcUser\Model\TuserTable');
				$user = $table->changepwd($_POST['cnfpwrd'],$userid);
			}
		}
		return new ViewModel();				
	}
	public function errorAlreadyActiveAction(){
		return new ViewModel();	
	}
	public function updatePasswordAction(){
		global $resetpasswordSubject;
		global $resetpasswordMessage;
		if(isset($_POST['fgtemail'])){
			$table = $this->getServiceLocator()->get('ZfcUser\Model\TuserTable');
			$user_id = $table->getuserid($_POST['fgtemail']);			
			if($user_id!=""){
				$table = $this->getServiceLocator()->get('ZfcUser\Model\TuserTable');
				$user = $table->changepwd($_POST['password'],$user_id->user_id);
				$tokentable=$this->getServiceLocator()->get('ZfcUser\Model\TforgotpasswordtokensTable');							
				$deletetokenid=$tokentable->deletetoken($_POST['tokenid']);	
				$to=$user_id->email_id;
				$username=ucfirst($user_id->first_name);
				$password=$_POST['password'];				
				$resetpasswordMessage = str_replace("<FULLNAME>","$username", $resetpasswordMessage);
				$resetpasswordMessage = str_replace("<PASSWORD>","$password", $resetpasswordMessage);
				if(sendMail($to,$resetpasswordSubject,$resetpasswordMessage)){				
					$result = new JsonModel(array(					
						'output' => 'success',
					));			
				}else{
					$result = new JsonModel(array(					
						'output' => 'not success',
					));
				}				
			}
		}
		return $result;		
	}
	public function checkPasswordAction(){
		$table = $this->getServiceLocator()->get('ZfcUser\Model\TuserTable');
		$user = $table->getpassword($_POST['oldpasswrd'],$_POST['userId']);		
		if($user>0){			
			$result = new JsonModel(array(					
				'output' => 'success',
			));			
		}else{
			$result = new JsonModel(array(					
				'output' => 'not success',
			));
		}
		return $result;		
	}	
    public function changeEmailAction()
    {
        // if the user isn't logged in, we can't change email
        if (!$this->zfcUserAuthentication()->hasIdentity()) {
            // redirect to the login redirect route
            return $this->redirect()->toRoute($this->getOptions()->getLoginRedirectRoute());
        }

        $form = $this->getChangeEmailForm();
        $request = $this->getRequest();
        $request->getPost()->set('identity', $this->getUserService()->getAuthService()->getIdentity()->getEmail());

        $fm = $this->flashMessenger()->setNamespace('change-email')->getMessages();
        if (isset($fm[0])) {
            $status = $fm[0];
        } else {
            $status = null;
        }

        $prg = $this->prg(static::ROUTE_CHANGEEMAIL);
        if ($prg instanceof Response) {
            return $prg;
        } elseif ($prg === false) {
            return array(
                'status' => $status,
                'changeEmailForm' => $form,
            );
        }

        $form->setData($prg);

        if (!$form->isValid()) {
            return array(
                'status' => false,
                'changeEmailForm' => $form,
            );
        }

        $change = $this->getUserService()->changeEmail($prg);

        if (!$change) {
            $this->flashMessenger()->setNamespace('change-email')->addMessage(false);
            return array(
                'status' => false,
                'changeEmailForm' => $form,
            );
        }

        $this->flashMessenger()->setNamespace('change-email')->addMessage(true);
        return $this->redirect()->toRoute(static::ROUTE_CHANGEEMAIL);
    }
    public function getUserService()
    {
        if (!$this->userService) {
            $this->userService = $this->getServiceLocator()->get('zfcuser_user_service');
        }
        return $this->userService;
    }
    public function setUserService(UserService $userService)
    {
        $this->userService = $userService;
        return $this;
    }
    public function setOptions(UserControllerOptionsInterface $options)
    {
        $this->options = $options;
        return $this;
    }
    public function getOptions()
    {
        if (!$this->options instanceof UserControllerOptionsInterface) {
            $this->setOptions($this->getServiceLocator()->get('zfcuser_module_options'));
        }
        return $this->options;
    }
	public function logoutAction(){	
		$sessiontable = $this->getServiceLocator()->get('ZfcUser\Model\TsessionTable');
		$sessiontable->updateUserID(session_id(),null);
		unset($_SESSION['user']);
		return $this->redirect()->toUrl('/');
		
	}	
	public function cofirmLoginAction(){		
		$result = new ViewModel();
		$result->setTerminal(true);
		return $result;	
	}
}
